<template>
    <div class="ai-layout">
        <div class="btn-ai" @click="handleAi">
            <img src="./style/image/log.png" class="ai-logo" alt="ai-logo">
        </div>
        <a-modal :open="open" width="720px" @cancel="handleCancel" :footer="null" >
            <template #title>
                <div ref="modalTitleRef" class="drag-header">{{ imgTitle }}</div>
            </template>
            <!-- 修改modalRender部分 -->
            <template #modalRender="{ originVNode }">
                <div :style="transformStyle">
                    <component :is="originVNode" />
                </div>
            </template>
            <div class="ai-chat-container">
                <!-- 消息区域 -->
                <div class="message-wrapper-layout">
                    <div class="welcome-card">
                        <div class="welcome-icon">
                            <img src="./style/image/fmt.webp" alt="icon">
                        </div>
                        <div class="welcome-content-wrapper">
                            <h4 class="welcome-title">{{ title }}</h4>
                            <span class="welcome-description">
                                {{ welcomeDescription }}
                            </span>
                        </div>
                    </div>
                    <!-- 添加滚动容器引用 -->
                    <div class="message-wrapper" ref="messageContainer">
                        <!-- 消息内容 -->
                        <div v-for="(msg, index) in messages" :key="index" :class="['message-bubble', msg.role]">
                            <div class="content">
                                <!--                                <span v-if="msg.role === 'ai'" class="ai-icon">▎</span>-->
                                <div v-if="msg.role === 'ai'" class="custom-markdown"
                                     v-html="msg.parsedContent || parseMarkdown(msg.content)"></div>
                                <template v-else>{{ msg.content }}</template>
                            </div>
                        </div>
                        <div class="append-tip" v-if="suggestedQuestions.length > 0">
                            <div class="append-tip_title">试着问问</div>
                            <div class="append-tip_group">
                                <div v-for="(question, index) in suggestedQuestions" :key="index" class="prompts-tip"
                                     @click="handleSuggestedQuestion(question)">
                                    <span>{{ question }}</span>
                                    <span class="tip-next">
                                    </span>
                                </div>
                            </div>
                            <!-- 加载状态 -->
                            <div v-if="loadingSuggestions" class="loading-suggestions">
                                正在加载建议问题...
                            </div>
                        </div>
                    </div>

                    <div v-if="loading" class="loading-wave">
                        <div class="wave-dot"></div>
                        <div class="wave-dot"></div>
                        <div class="wave-dot"></div>
                    </div>
                </div>

                <!-- 输入区域 -->
                <div class="input-layout">
                    <div class="input-tip" v-if="promptList.length > 0">
                        <section class="input-tip_item" @click="handlePrompts(item.label)"
                                 v-for="(item, key) in promptList" :key="key">
                            <div class="item-prompts_icon">
                                <img :src="item.icon" alt="icon" />
                            </div>
                            <div class="item-prompts_content">
                                <p class="prompts-desc">{{ item.label }}?</p>
                            </div>
                        </section>
                    </div>
                    <div class="input-area">
                        <a-input v-model:value="inputMessage" placeholder="输入你的问题..." @pressEnter="()=>sendMessage()"
                                 class="sci-input">
                            <template #suffix>
                                <a-tooltip title="停止生成" v-if="isStop">
                                    <div @click="stopMessage" class="stop-btn">
                                        <StopOutlined />
                                    </div>
                                </a-tooltip>
                                <a-tooltip title="发送" v-else>
                                    <div @click="()=>sendMessage()" class="send-btn">
                                        <ArrowUpOutlined />
                                    </div>
                                </a-tooltip>
                            </template>
                        </a-input>
                    </div>
                </div>
            </div>

        </a-modal>
    </div>

</template>
<script setup>
defineOptions({
    inheritAttrs: false,
    name:"AiAgent"
})
import { ref, reactive, defineProps, onMounted, nextTick, watch, } from 'vue';
// import light from './style/image/light-up.svg'
// import flame from './style/image/flame.svg'
// import books from './style/image/books.svg'
import { parseMarkdown } from './config/markdown-config'
import { message } from 'ant-design-vue';
import initDraggable from "./config/modal-drag";

const props = defineProps({
    imgTitle: {
        type: String,
        default: "AI助手"
    },
    title: {
        type: String,
        default: "Hello, 我是红迅Ai助手"
    },
    welcomeDescription: {
        type: String,
        default: "有关知识库的问题都可以向我提问~"
    },
    incomingInfo: {
        type: String,
        default: "我是智能ai助手"
    },
    chatMessage: {
        type: Object,
        default: {
            url: "http://dev.redxun.cn:8088/v1/chat-messages",
            Authorization: "Bearer app-1YjlZu6yW4hr1K03v0qLbAcV",
            body: {
                response_mode: "streaming",
                user: "abc-123",
                inputs: {},
            }
        }
    },
    promptList: {
        type: Array,
        default: []
    },
});
// const emits = defineEmits(['cancel']);

const open = ref(false);

const inputMessage = ref('');
const messages = reactive([]);
const loading = ref(false);
const isStop = ref(false)
const currentAiMessage = ref(null);
const controller = ref(null);
// 下一步状态
const suggestedQuestions = ref([])
const loadingSuggestions = ref(false)
const currentMessageId = ref(null)
// 消息容器引用
const messageContainer = ref(null)
// 初始化拖拽并获取返回值
const { transformStyle, modalTitleRef } = initDraggable();

// 自动滚动到底部
const scrollToBottom = () => {
    nextTick(() => {
        if (messageContainer.value) {
            messageContainer.value.scrollTop = messageContainer.value.scrollHeight
        }
    })
}

const sendMessage = async (externalQuery) => {

    try {
        inputMessage.value = externalQuery || inputMessage.value
        if (!inputMessage.value.trim()) {
            message.warning('请输入有效内容')
            return
        }

        // 中止之前的请求
        if (controller.value) {
            controller.value.abort()
        }

        // 添加用户消息
        messages.push({
            role: 'user',
            content: inputMessage.value
        })

        // 创建并存储AI消息
        currentAiMessage.value = {
            role: 'ai',
            content: ''
        }
        messages.push(currentAiMessage.value)

        loading.value = true;
        isStop.value = true;

        // 使用AbortController控制请求
        controller.value = new AbortController();

        const response = await fetch(props.chatMessage.url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json',
                'Authorization': props.chatMessage.Authorization
            },
            body: JSON.stringify({
                query: inputMessage.value,
                "response_mode": props.chatMessage.body.response_mode,
                "user": props.chatMessage.body.user,
                "inputs": props.chatMessage.body.inputs,
            }),
            signal: controller.value.signal
        });

        const reader = response.body.getReader();
        const decoder = new TextDecoder();

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            const chunk = decoder.decode(value);
            const lines = chunk.split('\n\n');

            lines.forEach(line => {
                try {
                    if (line.startsWith('data: ')) {
                        const eventData = JSON.parse(line.replace('data: ', ''));
                        // 确保message_id在消息结束时获取
                        if (eventData.event === 'message_end') {
                            currentMessageId.value = eventData.message_id;
                        }
                        if (eventData.event === 'message' && eventData.answer) {
                            const filteredContent = eventData.answer.replace(/<think>/g, '').replace(/<\/think>/g, '');
                            currentAiMessage.value.content += filteredContent;
                            currentAiMessage.value.parsedContent = parseMarkdown(currentAiMessage.value.content);
                            scrollToBottom();
                        }
                    }
                } catch (e) {
                    console.error('解析错误:', e);
                }
            });
        }
    } catch (error) {
        if (error.name !== 'AbortError') {
            message.error('请求失败: ' + error.message);
        }
    } finally {
        loading.value = false;
        isStop.value = false;
        inputMessage.value = '';
        controller.value = null;
        // 在消息处理完成后获取建议
        if (currentMessageId.value) {
            await fetchSuggestedQuestions(currentMessageId.value)
        }
        scrollToBottom()
    }
};


// 新增获取建议方法
const fetchSuggestedQuestions = async (messageId) => {
    try {
        loadingSuggestions.value = true;
        // 添加重试机制
        let retries = 3;
        while (retries > 0) {
            const response = await fetch(
                `http://dev.redxun.cn:8088/v1/messages/${messageId}/suggested?user=abc-123`,
                {
                    headers: {
                        'Authorization': 'Bearer app-1YjlZu6yW4hr1K03v0qLbAcV'
                    }
                }
            );

            if (response.status === 404 && retries > 0) {
                // 等待1秒后重试
                await new Promise(resolve => setTimeout(resolve, 1000));
                retries--;
                continue;
            }

            if (!response.ok) throw new Error('请求失败');

            let result = await response.json();
            suggestedQuestions.value = result.data;
            break;
        }
    } catch (error) {
        console.error('获取建议失败:', error);
    } finally {
        loadingSuggestions.value = false;
    }
}

// 处理建议问题点击
const handleSuggestedQuestion = (question) => {
    inputMessage.value = question
    sendMessage()
    suggestedQuestions.value = [] // 清空当前建议
}

const stopMessage = () => {
    if (controller.value) {
        controller.value.abort();
    }
    isStop.value = false;
};

function handlePrompts(sendInfo) {
    inputMessage.value = sendInfo;
    sendMessage();
    suggestedQuestions.value = [] // 清空当前建议
}
function handleAi() {
    open.value = true;
}
function handleCancel() {
    open.value = false;
}
watch(
    () => props.incomingInfo,
    (newVal) => {
        if (newVal) {
            // 中止正在进行的请求
            if (controller.value) {
                controller.value.abort()
            }
            // 清空当前消息
            messages.splice(0, messages.length)
            // 触发新请求
            sendMessage(newVal)
        }
    },
)
// 添加监听器确保新消息创建时滚动
watch(() => messages.length, () => {
    scrollToBottom()
})


</script>
<style scoped lang="scss">
@import "style/ai-agent";
</style>
